package com.lujieni.netty.c5;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.Charset;

public class HelloWorldServer {

    public static void main(String[] args) {


        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        new ServerBootstrap()
                // boss只负责ServerSocketChannel的accept事件  worker只负责socketChannel的读写事件
                .group(boss, worker)
                .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(16, 16, 16))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    // 在连接建立后被调用,仅仅是加了处理器而已
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {

                     //   ch.pipeline().addLast(new FixedLengthFrameDecoder(10));

                     //   ch.pipeline().addLast(new LineBasedFrameDecoder(512)); //split by (\n or \r\n)

                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024,0,4,0,4));

                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            int i = 1;
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf bb = (ByteBuf)msg;
                                String content = bb.toString(Charset.defaultCharset());
                                System.out.println((i++)+(":")+content);
                                super.channelRead(ctx, msg);
                            }
                        });

                     //   ch.pipeline().addLast(new LoggingHandler()); // 将ByteBuf转为String
                    }
                })
                .bind(8081);
    }
}
